# coding=utf-8
# FXJ 19373311@buaa.edu.cn
# This script must be put in the DIR artifacts
# # # # # # # # # # # # #
# artifacts <dir>
#     |-- xxx1_jar <dir>
#     |      |-- xxx1.jar
#     |      |-- *Result.txt
#     |-- xxx2_jar <dir>
#     |      |-- xxx2.jar
#     |      |-- *Result.txt
#     |-- *submit <dir>
#     |      |-- *stdin1.txt
#     |      |-- *stdout1.txt
#     |-- TestCases <dir>
#     |-- *Result.txt
#     |-- Hacker.py <this>
# # # # # # # # # # # # #
from sympy import *
import os
import subprocess


names = ["alterege", "archer", "assassin", "berserker", "caster", "lancer", "rider"]
myName = "saber"
readTestSetFromFile = True
testSet = []
ansSet = []
x = symbols("x")

def readTestSet():
    #TODO
    file = open("TestCases\\dataset.txt", "r")
    lines = file.readlines()
    file.close()
    return lines


def genTestSet():
    # TODO
    return []


def checkAns(standardAns, usrAns):
    if usrAns == None or usrAns == "":
        return False
    cmp = None
    try:
        cmp = simplify(standardAns - simplify(usrAns))
    except:
        return False
    finally:
        return cmp == 0


def getAnsSet(testSet):
    results = []
    for case in testSet:
        # TODO
        ans = simplify(case).diff()
        results.append(ans)
    return results


def writeUsrRes(student, usrWrongList, usrWrongAns):
    file = open(student + "_jar\\Result.txt", "w")
    length = len(usrWrongList)
    if length == 0:
        file.write("All correct!")
    else:
        file.write(str(length) + " wrong case(s):\n\n")
        for i in range(length):
            file.write(str(i + 1) + "  Case #" + str(usrWrongList[i]) + ":\n")
            file.write("stdin:\n")
            file.write(str(testSet[usrWrongList[i]]) + "\n")
            file.write("stdout:\n")
            file.write(str(usrWrongAns[i]) + "\n")
            file.write("ans:\n")
            file.write(str(ansSet[usrWrongList[i]]) + "\n\n")
    file.close()


def writeTotalRes(totalWrongList, totalWrongSet):
    file = open("Result.txt", "w")
    nOfP = len(names)
    for i in range(nOfP):
        file.write(names[i])
        if len(totalWrongList[i]) == 0:
            file.write(": All correct!\n\n")
        else:
            file.write(": " + str(len(totalWrongList[i])) + " wrong case(s) in total.\n")
            for k in totalWrongList[i]:
                file.write(str(k) + "\t")
            file.write("\n\n")
    file.close()
    nOfWA = len(totalWrongSet)
    tmp = list(totalWrongSet)
    if not os.path.exists("submit"):
        os.makedirs("submit")
    else:
        os.system("del /q submit\\*")
    for i in range(nOfWA):
        file = open("submit\\" + str(i + 1) +"_stdin.txt", "w")
        file.write(str(testSet[tmp[i]]))
        file.close()
        file = open("submit\\" + str(i + 1) +"_stdout.txt", "w")
        file.write(str(ansSet[tmp[i]]))
        file.close()


if __name__ == "__main__":
    os.system("cls")
    print("OOHacker")
    print("  19373311@buaa.edu.cn\n")
    print("Preparing test cases...")
    if readTestSetFromFile:
        testSet = readTestSet()
    else:
        testSet = genTestSet()
    nOfCases = len(testSet)
    ansSet = getAnsSet(testSet)
    totalWrongSet = set()
    totalWrongList = []
    print("Start testing, " + str(nOfCases) + " case(s) in total.\n")
    for student in names:
        dir = student + "_jar"
        usrWrongList = []
        usrWrongAns = []
        cmd = "java -jar " + student + ".jar"
        print("Testing " + student)
        for i in range(nOfCases):
            print("\tTesting " + student + ", Case #" + str(i) + ":", end="     ")
            try:
                usrAns = subprocess.run(cmd, shell=True, capture_output=True,
                                        cwd=dir, input=testSet[i],
                                        universal_newlines=True, timeout=5).stdout
            except:
                usrAns = ""
            else:
                pass
            if checkAns(ansSet[i], usrAns):
                print("AC")
            else:
                print("Wrong")
                usrWrongList.append(i)
                usrWrongAns.append(usrAns)
        print("Finish testing %s. " %(student), end="")
        if len(usrWrongList) == 0:
            print("All correct!\n")
        else:
            print("%d WRONG cases.\n" %(len(usrWrongList)))
        writeUsrRes(student, usrWrongList, usrWrongAns)
        totalWrongList.append(usrWrongList)
        totalWrongSet = totalWrongSet.union(set(usrWrongList))
    print("\nFinished all testing tasks, %d case(s) to submit. Saving results..."%(len(totalWrongSet)))
    writeTotalRes(totalWrongList, totalWrongSet)
    os.system("pause")